﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using fideeraSoft.Handlers;
using System.Drawing;
using System.Windows.Forms;
using fideeraSoft.Utils;
using System.Data.SqlClient;
using System.Data;

namespace fideeraSoft.Paneles
{
   public class ProductoPanelModificacion:PanelGeneral
    {
        private System.Windows.Forms.Button btBuscarProducto;
        private System.Windows.Forms.DataGridView dgvMostrarProductos;
        private System.Windows.Forms.TableLayoutPanel tlpBuscarProd;
        private System.Windows.Forms.Button btGuardarCambios;
        private System.Windows.Forms.TableLayoutPanel tlpBotones;
        private System.Windows.Forms.Button btVolver;
        private System.Windows.Forms.TextBox tbBuscarProducto;

        private int locationTlpBuscarProducto;
        private int locationBtCambios = 0;

        private SqlDataAdapter adapter;
        private DataSet ds;
        private DataSet changes;
        private SqlCommandBuilder cmdBuilder;

        public ProductoPanelModificacion(Handler handler)
        {
            this.formatearPanelGeneral(handler);

            InitializeComponent();

            this.formatearTableTitulo("MODIFICACIÓN DE PRODUCTO");

            string query = "SELECT ID AS [ID Producto], nombre AS Nombre_Variedad, codigo AS Código,descripcion AS Descripción,color AS Características, marca AS Marca FROM Producto";

            adapter = SQLclass.obtenerAdapter(query);
            if (adapter != null)
            {
                ds = new DataSet();
                adapter.Fill(ds);

                if (ds.Tables[0].Rows.Count <= 0)
                    MessageBox.Show("NO HAY NINGUN PRODUCTO CARGADO", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                dgvMostrarProductos.DataSource = ds.Tables[0];
                
                this.formatearDataGrid();

                this.formatearTablaBuscarProd();

                this.formatearTablaBotones();
                
                
                this.Controls.Add(dgvMostrarProductos);
                this.Controls.Add(tlpBuscarProd);
                this.Controls.Add(tlpBotones);    
            }

            else
            {
                //CLogger.Append("[ProveedorPanelMostrar] Lista Proveedor mostrar Null: ", CLogger.INFO);      //DEBUG
                MessageBox.Show("NO HAY NINGUN PRODUCTO CARGADO", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.handler.backToPrincipal();
            }
            
        }


        #region FORMATEAR

        private void formatearDataGrid()
        {
            dgvMostrarProductos.AutoGenerateColumns = true;
            dgvMostrarProductos.Size = new Size(this.Size.Width - 100, this.Size.Height - 400);
            dgvMostrarProductos.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.Fill);
            dgvMostrarProductos.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllHeaders);
            dgvMostrarProductos.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            dgvMostrarProductos.BorderStyle = BorderStyle.Fixed3D;
            
            dgvMostrarProductos.Location = new Point(MetodosGenerales.calcularCenterWidth(this.Size.Width, dgvMostrarProductos.Size.Width), this.InitialRealPointVertical);
        }

        private void formatearTablaBuscarProd()
        {                        
            
            //tlpBuscarProv.Size = new Size(lbBuscarProvCuil.Size.Width + tbBuscarProvCuil.Size.Width + 10,tbBuscarProvCuil.Size.Height);
            int wid = MetodosGenerales.calcularCenterWidth(handler.FormFrame.Size.Width, tlpBuscarProd.Size.Width);

            locationTlpBuscarProducto = this.InitialRealPointVertical + dgvMostrarProductos.Size.Height + 15;

            tlpBuscarProd.Location = new Point(wid, locationTlpBuscarProducto);

            tlpBuscarProd.Controls.Add(btBuscarProducto);
            tlpBuscarProd.Controls.Add(tbBuscarProducto);


        }

        private void formatearTablaBotones()
        {
            
            locationBtCambios = locationTlpBuscarProducto + tlpBuscarProd.Size.Height + 10;
            tlpBotones.Location = new Point(MetodosGenerales.calcularCenterWidth(this.handler.FormFrame.Size.Width, tlpBotones.Size.Width), locationBtCambios);

            tlpBotones.Controls.Add(btVolver);
            tlpBotones.Controls.Add(btGuardarCambios);

        }
       


        #endregion

        #region INICIALIZAR
        private void InitializeComponent()
        {
            this.btBuscarProducto = new System.Windows.Forms.Button();
            this.dgvMostrarProductos = new System.Windows.Forms.DataGridView();
            this.tlpBuscarProd = new System.Windows.Forms.TableLayoutPanel();
            this.btGuardarCambios = new System.Windows.Forms.Button();
            this.tbBuscarProducto = new System.Windows.Forms.TextBox();
            this.tlpBotones = new System.Windows.Forms.TableLayoutPanel();
            this.btVolver = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.dgvMostrarProductos)).BeginInit();
            this.SuspendLayout();
            // 
            // btBuscarProducto
            // 
            this.btBuscarProducto.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.btBuscarProducto.BackColor = System.Drawing.Color.AliceBlue;
            this.btBuscarProducto.Dock = System.Windows.Forms.DockStyle.Fill;
            this.btBuscarProducto.Font = new System.Drawing.Font("Bodoni MT", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btBuscarProducto.Location = new System.Drawing.Point(0, 0);
            this.btBuscarProducto.Name = "btBuscarProducto";
            this.btBuscarProducto.Size = new System.Drawing.Size(75, 23);
            this.btBuscarProducto.TabIndex = 0;
            this.btBuscarProducto.Text = "Buscar Producto (Código)";
            this.btBuscarProducto.UseVisualStyleBackColor = false;
            this.btBuscarProducto.Click += new System.EventHandler(this.btBuscarProducto_Click);
            // 
            // dgvMostrarProductos
            // 
            this.dgvMostrarProductos.AllowUserToResizeRows = false;
            this.dgvMostrarProductos.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dgvMostrarProductos.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnF2;
            this.dgvMostrarProductos.Location = new System.Drawing.Point(0, 0);
            this.dgvMostrarProductos.Name = "dgvMostrarProductos";
            this.dgvMostrarProductos.RowTemplate.DefaultCellStyle.Font = new System.Drawing.Font("Bodoni MT", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.dgvMostrarProductos.Size = new System.Drawing.Size(240, 150);
            this.dgvMostrarProductos.TabIndex = 0;
            this.dgvMostrarProductos.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvMostrarProductos_CellClick);
            this.dgvMostrarProductos.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvMostrarProductos_CellContentClick);
            // 
            // tlpBuscarProd
            // 
            this.tlpBuscarProd.BackColor = System.Drawing.Color.LightCyan;
            this.tlpBuscarProd.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single;
            this.tlpBuscarProd.ColumnCount = 2;
            this.tlpBuscarProd.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarProd.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarProd.Location = new System.Drawing.Point(0, 0);
            this.tlpBuscarProd.Name = "tlpBuscarProd";
            this.tlpBuscarProd.RowCount = 1;
            this.tlpBuscarProd.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarProd.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarProd.Size = new System.Drawing.Size(400, 40);
            this.tlpBuscarProd.TabIndex = 0;
            // 
            // btGuardarCambios
            // 
            this.btGuardarCambios.BackColor = System.Drawing.Color.AliceBlue;
            this.btGuardarCambios.Font = new System.Drawing.Font("Bodoni MT", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btGuardarCambios.Location = new System.Drawing.Point(0, 0);
            this.btGuardarCambios.Margin = new System.Windows.Forms.Padding(12, 3, 3, 3);
            this.btGuardarCambios.Name = "btGuardarCambios";
            this.btGuardarCambios.Size = new System.Drawing.Size(75, 40);
            this.btGuardarCambios.TabIndex = 0;
            this.btGuardarCambios.Text = "Guardar";
            this.btGuardarCambios.UseVisualStyleBackColor = false;
            this.btGuardarCambios.Click += new System.EventHandler(this.btGuardarCambios_Click);
            // 
            // tbBuscarProducto
            // 
            this.tbBuscarProducto.Font = new System.Drawing.Font("Bodoni MT", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.tbBuscarProducto.Location = new System.Drawing.Point(0, 0);
            this.tbBuscarProducto.MaxLength = 50;
            this.tbBuscarProducto.Name = "tbBuscarProducto";
            this.tbBuscarProducto.Size = new System.Drawing.Size(200, 30);
            this.tbBuscarProducto.TabIndex = 0;
            // 
            // tlpBotones
            // 
            this.tlpBotones.BackColor = System.Drawing.Color.LightCyan;
            this.tlpBotones.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single;
            this.tlpBotones.ColumnCount = 2;
            this.tlpBotones.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBotones.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBotones.Location = new System.Drawing.Point(0, 0);
            this.tlpBotones.Name = "tlpBotones";
            this.tlpBotones.RowCount = 1;
            this.tlpBotones.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBotones.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBotones.Size = new System.Drawing.Size(200, 46);
            this.tlpBotones.TabIndex = 0;
            // 
            // btVolver
            // 
            this.btVolver.BackColor = System.Drawing.Color.AliceBlue;
            this.btVolver.Font = new System.Drawing.Font("Bodoni MT", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btVolver.Location = new System.Drawing.Point(0, 0);
            this.btVolver.Margin = new System.Windows.Forms.Padding(12, 3, 3, 3);
            this.btVolver.Name = "btVolver";
            this.btVolver.Size = new System.Drawing.Size(75, 40);
            this.btVolver.TabIndex = 0;
            this.btVolver.Text = "Volver";
            this.btVolver.UseVisualStyleBackColor = false;
            this.btVolver.Click += new System.EventHandler(this.btVolver_Click);
            ((System.ComponentModel.ISupportInitialize)(this.dgvMostrarProductos)).EndInit();
            this.ResumeLayout(false);

        }
        #endregion

        private void btVolver_Click(object sender, EventArgs e)
        {
            this.handler.backToPrincipal();
        }

        private void btGuardarCambios_Click(object sender, EventArgs e)
        {   
            try
            {
                if (dgvMostrarProductos.CurrentCell == null)
                {
                    MessageBox.Show("NO HAY DATOS EN LA TABLA", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                
                }

                if (adapter != null)
                {
                    cmdBuilder = new SqlCommandBuilder(adapter);
                    changes = ds.GetChanges();
                    if (changes != null)
                    {
                        adapter.Update(changes);
                        MessageBox.Show("CAMBIOS GUARDADOS", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        this.handler.backToPrincipal();
                    }
                    else
                    {
                        MessageBox.Show("NO HAY CAMBIOS EN LA TABLA", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }

                }
            }
            catch (Exception exc)
            {
                MessageBox.Show("ERROR AL GUARDAR LOS DATOS.\nNo se guardaran los datos. \nVerifique celdas modificadas y cantidad de dígitos modificados.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                CLogger.Append("[btGuardarCambios_Click] Exception: " + exc, CLogger.ERROR);      //DEBUG
                this.handler.backToPrincipal();
            }
        }

        private void btBuscarProducto_Click(object sender, EventArgs e)
        {
            if (dgvMostrarProductos.CurrentCell == null)
            {
                MessageBox.Show("NO HAY DATOS EN LA TABLA.", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (dgvMostrarProductos.Rows.Count <= 0)
                return;


            dgvMostrarProductos.ClearSelection();
            if (!string.IsNullOrWhiteSpace(tbBuscarProducto.Text))
            {
                string searchValue = tbBuscarProducto.Text;
                
                
                try
                {                    
                    foreach (DataGridViewRow row in dgvMostrarProductos.Rows)
                    {                        
                        if (row.Cells[2].Value.ToString().Equals(searchValue))
                        {
                            dgvMostrarProductos.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                            row.Selected = true;

                            dgvMostrarProductos.CurrentCell = row.Cells[0];
                            //MessageBox.Show("ENCONTRE: "+inRowFinded, "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            tbBuscarProducto.Clear();
                            break;

                        }
                        
                    }
                }
                catch (Exception exc)
                {
                    tbBuscarProducto.Clear();
                    MessageBox.Show("NO SE ENCONTRO EL PRODUCTO", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                   // CLogger.Append("[btBuscarProducto_Click] Exception: " + exc, CLogger.ERROR);      //DEBUG
                }
            }
            else
            {
                MessageBox.Show("NO SE INGRESO CÓDIGO A BUSCAR", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            }
        }

        private void dgvMostrarProductos_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //dgvMostrarProductos.SelectionMode = DataGridViewSelectionMode.CellSelect;
        }

        private void dgvMostrarProductos_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            dgvMostrarProductos.SelectionMode = DataGridViewSelectionMode.CellSelect;
        }
    }
}
